#!/bin/bash
tempfile=".test_output.tmp"

# Ensure rtp dependencies are installed
if [ ! -d .testdeps ]; then
	mkdir -p .testdeps

	git clone --depth 1 https://github.com/nvim-lua/plenary.nvim.git .testdeps/plenary.nvim
	git clone --depth 1 https://github.com/nvim-treesitter/nvim-treesitter.git .testdeps/nvim-treesitter
	git clone --depth 1 https://github.com/nvim-neotest/neotest.git .testdeps/neotest
	git clone --depth 1 https://github.com/nvim-neotest/nvim-nio.git .testdeps/nvim-nio
fi

if [[ -n $1 ]]; then
	nvim --headless --noplugin -u tests/minimal_init.vim -c "PlenaryBustedFile $1" | tee "${tempfile}"
else
	nvim --headless --noplugin -u tests/minimal_init.vim -c "PlenaryBustedDirectory tests/ {minimal_init = 'tests/minimal_init.vim'}" | tee "${tempfile}"
fi

# Plenary doesn't emit exit code 1 when tests have errors during setup
errors=$(sed 's/\x1b\[[0-9;]*m//g' "${tempfile}" | awk '/(Errors|Failed) :/ {print $3}' | grep -v '0')

rm "${tempfile}"

if [[ -n $errors ]]; then
	echo "Tests failed"
	exit 1
fi

exit 0
